#-*- coding:utf-8 -*-
import numpy as np 
import cv2
import time
from config import Config
import tensorflow as tf
    

config = Config()
COLOR_WHITE = (255,255,255)
COLOR_BLACK = (0,0,0)
COLOR_BORDER = (0,0,255)

def myDraw(images,loc,winSize=(30,30)):
    winSize=np.array((config.win_size_forTest,config.win_size_forTest))
    images=tf.reshape(images,[-1, config.img_sz, config.img_sz, config.strokeMap_channels])
    counter=tf.shape(images)[0]
    #images=tf.pack(images)
    with tf.Session() as sess:
          images=sess.run(images)
          counter=sess.run(counter)
          #loc=sess.run(loc).tolist()
    strokes=np.zeros((counter,config.img_sz, config.img_sz, config.strokeMap_channels))
    for i in range(counter):
       img=np.array(images[i])
       img = img.astype(np.uint8)
       loc_this=loc[i,:]
       width,height = loc_this[0],loc_this[1]
       width = width*config.img_sz/2.0 + config.img_sz/2.0
       height = height*config.img_sz/2.0 + config.img_sz/2.0
       loc_this = np.array([width,height])
       stroke=manualDraw(img,loc_this,winSize)
       strokes[i,:,:,:]=stroke
    return strokes
         

def manualDraw(img,winLoc,winSize):
  def draw_call(event,x,y,flags,param):
    global img2,cmode
    winSize_half = winSize/2.0
    leftup = tuple((winLoc-winSize_half).astype(np.int16).tolist())
    rightdown = tuple((winLoc+winSize_half).astype(np.int16).tolist())
    if event == cv2.EVENT_LBUTTONDOWN:
      if cmode == True:  #前景
        cv2.rectangle(img2,leftup,rightdown,COLOR_WHITE,-1)
      else:  #背景
        cv2.rectangle(img2,leftup,rightdown,COLOR_BLACK,-1)
    
  def img_with_shadow(img2,winLoc,winSize):
    img = img2.copy()
    winSize_half = winSize/2.0
    leftup = tuple((winLoc-winSize_half).astype(np.int16).tolist())
    rightdown = tuple((winLoc+winSize_half).astype(np.int16).tolist())
    cv2.rectangle(img,leftup,rightdown,COLOR_BORDER,2)
    return img
  global img2,drawing,cmode,ix,iy,jx,jy
  img2 = img.copy()
  drawing = False
  cmode = False
  ix = iy = jx = jy = -1
  cv2.namedWindow('Image')
  cv2.setMouseCallback('Image',draw_call)
  while(True):
    img3 = img_with_shadow(img2,winLoc,winSize)
    cv2.imshow('Image',img3)
    k = cv2.waitKey(1)&0xFF
    if k == ord('f'): #前景
      cmode = True
    elif k == ord('b'): #背景
      cmode = False
    elif k == ord('n'): #保存
      img = img2
    elif k == 27:     #ESC
      break
    time.sleep(0.05)
  cv2.destroyAllWindows()
  return img
  
